const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 分页列物资申请
router.get("/list", async function (req, res, next) {
  const where = {};
  const where2 = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const name = req.query.name;
  const type = req.query.type;
  const personId = req.query.personId;
  const status = req.query.status;
  if (type) {
    where.applyType = {
      [Op.like]: type,
    };
  }
  if (personId) {
    where.personId = {
      [Op.like]: personId,
    };
  }
  if (status) {
    if (status == 0) {
      where.status = {
        [Op.in]: [0, 4],
      };
    } else if (status == 1) {
      where.status = {
        [Op.in]: [1, 2, 3, 5],
      };
    }
  }
  if (name) {
    where2.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  const result = await models.GoodsApply.findAndCountAll({
    attributes: [
      "id",
      "status",
      "applyNumber",
      "applyReason",
      "createdAt",
      "updatedAt",
      "applyType",
    ],
    include: [
      {
        attributes: ["username", "name", "stuCode", "phone", "role", "gender"],
        model: models.User,
        include: [
          {
            attributes: ["name"],
            model: models.College,
          },
          {
            attributes: ["name"],
            model: models.Major,
          },
          {
            attributes: ["name"],
            model: models.Grade,
          },
          {
            attributes: ["name"],
            model: models.Society,
          },
        ],
      },
      {
        attributes: [
          "name",
          "price",
          "unit",
          "goodsInfo",
          "stockNum",
          "createdAt",
        ],
        model: models.Good,
        where: where2,
      },
    ],
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
    where: where,
    order: [["updatedAt", "asc"]], // 根据某个字段进行排序， desc-降序 asc-升序
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增物资申请
router.post("/", async function (req, res, next) {
  models.GoodsApply.create({
    personId: req.body.personId,
    goodsId: req.body.goodsId,
    applyType: req.body.applyType,
    applyNumber: req.body.applyNumber,
    applyReason: req.body.applyReason,
    status: 0,
  }).then((res) => {
    models.GoodsRecord.create({
      personId: req.body.personId,
      applyId: res.id,
      status: 0,
      remark: req.body.applyReason,
    });
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 审批/操作物资申请
router.put("/", async function (req, res, next) {
  const status = req.body.status;
  const id = req.body.id;
  const personId = req.body.personId;
  const remark = req.body.remark;
  // 申请状态：0-待审批，1-同意申请 2-驳回申请 3-待归还 4-归还待审批 5-同意归还 6 -拒绝归还
  const result = await models.GoodsApply.findByPk(id);
  result.update({ status: status });
  if (status == 3) {
    // 将物资表数据修改
    await models.Good.findByPk(result.goodsId).then((res)=> {
      res.update({ stockNum: res.stockNum - result.applyNumber });
    })
    
  } else if (status == 5) {
    // 将物资的数量+回来
    const result2 = await models.Good.findByPk(id);
    result2.update({ stockNum: result2.stockNum + result.applyNumber });
  } else if (status == 6) {
    result.update({ status: 3 });
  }
  models.GoodsRecord.create({
    applyId: result.id,
    personId: personId,
    status: status,
    remark: remark,
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

module.exports = router;
